#! _*_ coding: utf8 _*_
import datetime
import sys, json
from itertools import chain

from student.models import Student, SClass
from django.contrib.auth.models import User
from accounts.models import UserProfile
from django import template
from django.core import serializers

register = template.Library()


def app_info(request):
    agent = request.META.get('HTTP_USER_AGENT', None)
    app_name = 'Roing'
    app_version = agent[len(app_name) + 1: agent.index(' ')]
    return {
        'version': app_version
    }


def reset_name():
    """只使用first_name"""
    for u in User.objects.all():
        if u.last_name:
            name = u.last_name + u.first_name
            u.last_name = ''
            u.first_name = name
            u.save()


@register.filter
def spt(value, s):
    return value.split(s)


def to_json(model, **argvs):
    model_fields = argvs.get('model_fields', None)
    fields = argvs.get('fields', None)
    json_model = json.loads(serializers.serialize('json', model))
    for index in range(len(json_model)):
        for model_field in model_fields:
            if hasattr(model[index], model_field):
                m_field = getattr(model[index], model_field)

    return json_model


def user_of_username(username, name):
    user = None
    try:
        user = User.objects.get(username=username)
    except Exception as e:
        last_name = name[:3]
        first_name = name[3:]
        user = User.objects.create(username=username, first_name=first_name, last_name=last_name)
        userprofile = UserProfile.objects.create(user=user)
        userprofile.desc = name + u'小朋友'
        userprofile.save()
        user.save()
    return user


def fill_desc_of_profile():
    reload(sys)
    sys.setdefaultencoding('utf8')
    users = User.objects.all()
    for user in users:
        up = user.userprofile
        if not up.desc:
            up.desc = user.last_name + user.first_name + r'小朋友'
            up.save()


def import_courses(file_name):
    reload(sys)
    sys.setdefaultencoding('utf8')
    f = open(file_name, 'r')
    while True:
        line = f.readline()
        if not line:
            break
        parts = line.split(' ')
        weekday = parts[0]
        username = parts[1]

        name = parts[2]

        begin = parts[3]
        end = parts[4][:-1]

        begin_time = datetime.datetime.strptime(begin, '%H:%M')
        end_time = datetime.datetime.strptime(end, '%H:%M')
        duration = end_time - begin_time

        user = user_of_username(username, name)

        student = None
        try:
            student = Student.objects.get(me=user)
        except Exception as e:
            student = Student.objects.create(me=user)

        clz = SClass.objects.create(weekday=int(weekday), begin=begin_time.time(), duration=duration)
        student.classes.add(clz)
        student.save()

    f.close()


def merge_list(*args):
    """
    交叉合并列表
    :param args: 列表入参
    :return: 合并后的列表
    """

    max_len = max([len(x) for x in args])
    for l in args:
        for i in range(max_len - len(l)):
            l.append(None)

    result = list(chain.from_iterable(zip(*args)))
    while None in result:
        result.remove(None)

    return result